package com.zjm.zdk.callback;

/**
 * 回调模式 use case
 */
public class TestCallBack {
    public static void main(String[] args) {

        Server server = new Server();
        Client client = new Client(server);
        client.sendMsg("Server, Hello~");
    }

    interface CSCallBack {
        void process(String status);
    }

    static class Client implements CSCallBack {

        Server server;

        public Client(Server server) {
            this.server = server;
        }

        public void sendMsg(final String msg) {
            System.out.println("客户端：发送的消息为：" + msg);
            new Thread(() -> {
                server.getClientMsg(this, msg);
            }).start();
            System.out.println("客户端：异步发送成功");
        }

        @Override
        public void process(String status) {
            System.out.println("客户端：收到服务端响应，响应状态" + status);
        }
    }

    static class Server {
        public void getClientMsg(CSCallBack csCallBack, String msg) {
            System.out.println("服务端：接收到客户端收到的消息：" + msg);
            try {
                Thread.sleep(5000);
                System.out.println("服务端：干活5秒钟");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String status = "200";
            System.out.println("服务端：客户端消息处理完成,返回状态" + status);
            csCallBack.process(status);
        }
    }
}

